package com.wanli.security;
import cn.hutool.json.JSONUtil;
import com.wanli.common.Result;
import com.wanli.domain.entity.User;
import com.wanli.service.UserService;
import com.wanli.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    JwtUtil jwtUtil;
    @Autowired
    UserService userService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //登录成功：就可以authentication对象取得登录用户名
        String username = authentication.getName();

        response.setContentType("application/json;charset=utf-8");
        ServletOutputStream out = response.getOutputStream();

        //获得登录成功用户信息  目前是静态登录（使用是配置用户root 123），改为动态登录
        User user = userService.getUserByUsername(username);

        //产生token，需要将token加入相应头，返回Vue端
        String token = jwtUtil.createToken(username);
        System.out.println(jwtUtil.getHeader());
        //将产生token存入到响应头中，返回给Vue端
        response.setHeader(jwtUtil.getHeader(),token);
        log.info("token==={}",token);

        Result success = Result.success(user);
        out.write(JSONUtil.toJsonStr(success).getBytes("utf-8") );
        out.flush();
        out.close();
    }
}
